Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources

In [1]:
# The new version of dataset is only available in the tfds-nightly package.
%pip --no-cache-dir install tensorflow-datasets --user
# DON'T MISS TO RESTART THE KERNEL
Requirement already satisfied: tensorflow-datasets in /opt/conda/lib/python3.7/site-packages (1.2.0)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.22.0)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (4.36.1)
Requirement already satisfied: attrs in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (19.3.0)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.2.1)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.12.0)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.8.1)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.17.4)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.3.1.1)
Requirement already satisfied: protobuf>=3.6.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (3.11.2)
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.14.0)
Requirement already satisfied: wrapt in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.11.2)
Requirement already satisfied: psutil in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (5.6.7)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.1.0)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.18.2)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (1.24.2)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (3.0.4)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2.8)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2019.11.28)
Requirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from protobuf>=3.6.1->tensorflow-datasets) (41.4.0)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tensorflow-datasets) (1.6.0)
Note: you may need to restart the kernel to use updated packages.
In [1]:
%pip --no-cache-dir install tfds-nightly --user
!pip install tensorflow --upgrade --user
Collecting tfds-nightly
  Downloading https://files.pythonhosted.org/packages/a6/7e/d1e386a8cba96f909d5e8a5e48a690d530470f739e0ab1a9cf597bc40d94/tfds_nightly-4.4.0.dev202111100107-py3-none-any.whl (4.0MB)
     |████████████████████████████████| 4.0MB 4.9MB/s eta 0:00:01
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.3.1.1)
Collecting typing-extensions; python_version < "3.8"
  Downloading https://files.pythonhosted.org/packages/74/60/18783336cc7fcdd95dae91d73477830aa53f5d3181ae4fe20491d7fc3199/typing_extensions-3.10.0.2-py3-none-any.whl
Collecting importlib-resources; python_version < "3.9"
  Downloading https://files.pythonhosted.org/packages/24/1b/33e489669a94da3ef4562938cd306e8fa915e13939d7b8277cb5569cb405/importlib_resources-5.4.0-py3-none-any.whl
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.12.0)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.17.4)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.22.0)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.2.1)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.8.1)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (4.36.1)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.1.0)
Collecting protobuf>=3.12.2
  Downloading https://files.pythonhosted.org/packages/4a/81/1722e657aea5abf8ed5da6f9ff1c5e4350f64be10de0a4ca6800fa30f06d/protobuf-3.19.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.1MB)
     |████████████████████████████████| 1.1MB 32.1MB/s eta 0:00:01
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.14.0)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.18.2)
Collecting zipp>=3.1.0; python_version < "3.10"
  Downloading https://files.pythonhosted.org/packages/bd/df/d4a4974a3e3957fd1c1fa3082366d7fff6e428ddb55f074bf64876f8e8ad/zipp-3.6.0-py3-none-any.whl
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2019.11.28)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (1.24.2)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tfds-nightly) (1.6.0)
Installing collected packages: typing-extensions, zipp, importlib-resources, protobuf, tfds-nightly
  WARNING: The script tfds is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed importlib-resources-5.4.0 protobuf-3.19.1 tfds-nightly-4.4.0.dev202111100107 typing-extensions-3.10.0.2 zipp-3.6.0
Note: you may need to restart the kernel to use updated packages.
Collecting tensorflow
  Downloading https://files.pythonhosted.org/packages/e8/02/d981f022c0232d692db870501c4198cb9de2d6f00b50ee84e58fa755ca84/tensorflow-2.7.0-cp37-cp37m-manylinux2010_x86_64.whl (489.6MB)
     |████████████████████████████████| 489.6MB 24kB/s s eta 0:00:01   |██▏                             | 33.3MB 5.0MB/s eta 0:01:32     |█████████████                   | 198.9MB 59.8MB/s eta 0:00:05     |██████████████████████          | 335.2MB 31.6MB/s eta 0:00:05
Collecting libclang>=9.0.1
  Downloading https://files.pythonhosted.org/packages/76/2d/7b0f7f5519669f11e66028fa227d4bcda4d77411d52d26c661676db82338/libclang-12.0.0-py2.py3-none-manylinux1_x86_64.whl (13.4MB)
     |████████████████████████████████| 13.4MB 38.4MB/s eta 0:00:01
Collecting tensorflow-estimator<2.8,~=2.7.0rc0
  Downloading https://files.pythonhosted.org/packages/db/de/3a71ad41b87f9dd424e3aec3b0794a60f169fa7e9a9a1e3dd44290b86dd6/tensorflow_estimator-2.7.0-py2.py3-none-any.whl (463kB)
     |████████████████████████████████| 471kB 44.2MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: absl-py>=0.4.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.8.1)
Collecting flatbuffers<3.0,>=1.12
  Downloading https://files.pythonhosted.org/packages/3d/d0/26033c70d642fbc1e35d3619cf3210986fb953c173b1226709f75056c149/flatbuffers-2.0-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: google-pasta>=0.1.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.1.8)
Requirement already satisfied, skipping upgrade: wheel<1.0,>=0.32.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.33.6)
Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (3.1.0)
Collecting tensorboard~=2.6
  Downloading https://files.pythonhosted.org/packages/2d/eb/80f75ab480cfbd032442f06ec7c15ef88376c5ef7fd6f6bf2e0e03b47e31/tensorboard-2.7.0-py3-none-any.whl (5.8MB)
     |████████████████████████████████| 5.8MB 27.8MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: protobuf>=3.9.2 in /root/.local/lib/python3.7/site-packages (from tensorflow) (3.19.1)
Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Collecting grpcio<2.0,>=1.24.3
  Downloading https://files.pythonhosted.org/packages/be/55/c4e63d514c4b5f14bd1bb6357c12c61d63f6bfe338e272ea350b7c8f351a/grpcio-1.41.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.9MB)
     |████████████████████████████████| 3.9MB 24.0MB/s eta 0:00:01
Collecting keras<2.8,>=2.7.0rc0
  Downloading https://files.pythonhosted.org/packages/6b/8b/065f94ba03282fa41b2d76942b87a180a9913312c4611ea7d6508fbbc114/keras-2.7.0-py2.py3-none-any.whl (1.3MB)
     |████████████████████████████████| 1.3MB 35.2MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: wrapt>=1.11.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.11.2)
Requirement already satisfied, skipping upgrade: h5py>=2.9.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (2.9.0)
Requirement already satisfied, skipping upgrade: numpy>=1.14.5 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.17.4)
Collecting keras-preprocessing>=1.1.1
  Downloading https://files.pythonhosted.org/packages/79/4c/7c3275a01e12ef9368a892926ab932b33bb13d55794881e3573482b378a7/Keras_Preprocessing-1.1.2-py2.py3-none-any.whl (42kB)
     |████████████████████████████████| 51kB 8.1MB/s  eta 0:00:01
Requirement already satisfied, skipping upgrade: typing-extensions>=3.6.6 in /root/.local/lib/python3.7/site-packages (from tensorflow) (3.10.0.2)
Requirement already satisfied, skipping upgrade: gast<0.5.0,>=0.2.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.2.2)
Requirement already satisfied, skipping upgrade: six>=1.12.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.12.0)
Collecting tensorflow-io-gcs-filesystem>=0.21.0
  Downloading https://files.pythonhosted.org/packages/7f/89/22984ef36a4797fa3bf9660dd45bc841a6e3d8f7a0cdacaa62617cd54a90/tensorflow_io_gcs_filesystem-0.21.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (2.1MB)
     |████████████████████████████████| 2.1MB 40.4MB/s eta 0:00:01
Collecting astunparse>=1.6.0
  Downloading https://files.pythonhosted.org/packages/2b/03/13dde6512ad7b4557eb792fbcf0c653af6076b81e5941d36ec61f7ce6028/astunparse-1.6.3-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: setuptools>=41.0.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (41.4.0)
Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (2.22.0)
Collecting google-auth-oauthlib<0.5,>=0.4.1
  Downloading https://files.pythonhosted.org/packages/b1/0e/0636cc1448a7abc444fb1b3a63655e294e0d2d49092dc3de05241be6d43c/google_auth_oauthlib-0.4.6-py2.py3-none-any.whl
Collecting tensorboard-plugin-wit>=1.6.0
  Downloading https://files.pythonhosted.org/packages/1a/c1/499e600ba0c618b451cd9c425ae1c177249940a2086316552fee7d86c954/tensorboard_plugin_wit-1.8.0-py3-none-any.whl (781kB)
     |████████████████████████████████| 788kB 39.7MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (0.16.0)
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (3.1.1)
Collecting tensorboard-data-server<0.7.0,>=0.6.0
  Downloading https://files.pythonhosted.org/packages/60/f9/802efd84988bffd9f644c03b6e66fde8e76c3aa33db4279ddd11c5d61f4b/tensorboard_data_server-0.6.1-py3-none-manylinux2010_x86_64.whl (4.9MB)
     |████████████████████████████████| 4.9MB 25.1MB/s eta 0:00:01
Collecting google-auth<3,>=1.6.3
  Downloading https://files.pythonhosted.org/packages/6a/f7/06cbd5ebfba40a9d51df6217f9325317d824234400454aebcf014e2eee38/google_auth-2.3.3-py2.py3-none-any.whl (155kB)
     |████████████████████████████████| 163kB 50.5MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (2019.11.28)
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (3.0.4)
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (2.8)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (1.24.2)
Collecting requests-oauthlib>=0.7.0
  Downloading https://files.pythonhosted.org/packages/a3/12/b92740d845ab62ea4edf04d2f4164d82532b5a0b03836d4d4e71c6f3d379/requests_oauthlib-1.3.0-py2.py3-none-any.whl
Collecting rsa<5,>=3.1.4; python_version >= "3.6"
  Downloading https://files.pythonhosted.org/packages/e9/93/0c0f002031f18b53af7a6166103c02b9c0667be528944137cc954ec921b3/rsa-4.7.2-py3-none-any.whl
Collecting cachetools<5.0,>=2.0.0
  Downloading https://files.pythonhosted.org/packages/ea/c1/4740af52db75e6dbdd57fc7e9478439815bbac549c1c05881be27d19a17d/cachetools-4.2.4-py3-none-any.whl
Collecting pyasn1-modules>=0.2.1
  Downloading https://files.pythonhosted.org/packages/95/de/214830a981892a3e286c3794f41ae67a4495df1108c3da8a9f62159b9a9d/pyasn1_modules-0.2.8-py2.py3-none-any.whl (155kB)
     |████████████████████████████████| 163kB 47.7MB/s eta 0:00:01
Collecting oauthlib>=3.0.0
  Downloading https://files.pythonhosted.org/packages/e8/5d/9dd1c29e5a786525f6342f6c1d812ed2e37edc653ad297048c1668988053/oauthlib-3.1.1-py2.py3-none-any.whl (146kB)
     |████████████████████████████████| 153kB 27.8MB/s eta 0:00:01
Collecting pyasn1>=0.1.3
  Downloading https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl (77kB)
     |████████████████████████████████| 81kB 321kB/s  eta 0:00:01
Installing collected packages: libclang, tensorflow-estimator, flatbuffers, grpcio, oauthlib, requests-oauthlib, pyasn1, rsa, cachetools, pyasn1-modules, google-auth, google-auth-oauthlib, tensorboard-plugin-wit, tensorboard-data-server, tensorboard, keras, keras-preprocessing, tensorflow-io-gcs-filesystem, astunparse, tensorflow
  WARNING: The scripts pyrsa-decrypt, pyrsa-encrypt, pyrsa-keygen, pyrsa-priv2pub, pyrsa-sign and pyrsa-verify are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script google-oauthlib-tool is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script tensorboard is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts estimator_ckpt_converter, import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed astunparse-1.6.3 cachetools-4.2.4 flatbuffers-2.0 google-auth-2.3.3 google-auth-oauthlib-0.4.6 grpcio-1.41.1 keras-2.7.0 keras-preprocessing-1.1.2 libclang-12.0.0 oauthlib-3.1.1 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-oauthlib-1.3.0 rsa-4.7.2 tensorboard-2.7.0 tensorboard-data-server-0.6.1 tensorboard-plugin-wit-1.8.0 tensorflow-2.7.0 tensorflow-estimator-2.7.0 tensorflow-io-gcs-filesystem-0.21.0
In [1]:
import warnings
warnings.filterwarnings('ignore')

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import numpy as np
import matplotlib.pyplot as plt

import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub
import pandas as pd
tfds.disable_progress_bar()
In [2]:
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
In [3]:
# TODO: Make all other necessary imports.
import json
import seaborn as sns

from tensorflow.keras.preprocessing.image import ImageDataGenerator, apply_affine_transform

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [4]:
# Download data to default local directory "~/tensorflow_datasets"
!python -m tensorflow_datasets.scripts.download_and_prepare --register_checksums=True --datasets=oxford_flowers102

# TODO: Load the dataset with TensorFlow Datasets. Hint: use tfds.load()
dataset, dataset_info = tfds.load('oxford_flowers102', as_supervised=True, with_info=True)
# TODO: Create a training set, a validation set and a test set.
training, testing, validation = dataset['train'], dataset['test'], dataset['validation']
2021-11-10 18:04:53.594332: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2021-11-10 18:04:53.594407: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
  File "/opt/conda/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/opt/conda/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/root/.local/lib/python3.7/site-packages/tensorflow_datasets/scripts/download_and_prepare.py", line 25, in <module>
    from tensorflow_datasets.scripts.cli import main as main_cli
  File "/root/.local/lib/python3.7/site-packages/tensorflow_datasets/scripts/cli/main.py", line 40, in <module>
    from tensorflow_datasets.scripts.utils import flag_utils
ModuleNotFoundError: No module named 'tensorflow_datasets.scripts.utils'

Explore the Dataset

In [5]:
# TODO: Get the number of examples in each set from the dataset info.
num_classes = dataset_info.features['label'].num_classes
print(f'The number of classes: {num_classes:,}')

# TODO: Get the number of classes in the dataset from the dataset info.
num_training_examples = dataset_info.splits['train'].num_examples
print(f'The number of observations/instances: {num_training_examples:,}')
The number of classes: 102
The number of observations/instances: 1,020
In [6]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in training.take(3):
    print(f'The image has shape: {image.shape} with label: {label}')
The image has shape: (500, 667, 3) with label: 72
The image has shape: (500, 666, 3) with label: 84
The image has shape: (670, 500, 3) with label: 70
In [7]:
# TODO: Plot 1 image from the training set.
for image, label in training.take(1):
    image = image.numpy().squeeze()
    label = label.numpy()

# Set the title of the plot to the corresponding image label. 
    plt.figure(figsize=[15,10])
    plt.imshow(image, cmap=plt.cm.binary)
    plt.title(f'This flower has label: {str(label)}')
    plt.colorbar()
    plt.show()

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [8]:
with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [9]:
class_names['72']
Out[9]:
'azalea'
In [10]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 
for image, label in training.take(1):
    image = image.numpy().squeeze()
    label = label.numpy()
    plt.figure(figsize=[15,10])
    plt.imshow(image, cmap=plt.cm.binary)
    plt.title(f'This flower is an {class_names[str(label)].title()}')
    plt.colorbar()
    plt.show()

Create Pipeline

In [11]:
batch_size = 32
image_size = 224

def normalize_and_resize(image, label):
    ''' Normalize and resize an image
    
        params:
            image - an image in the dataset
            label - a label
    '''
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, [image_size, image_size])
    image /= 255
    return (image, label)
In [12]:
data_augmentation = tf.keras.Sequential([
  tf.keras.layers.RandomFlip("horizontal_and_vertical"),
  tf.keras.layers.RandomRotation(0.2),
  tf.keras.layers.RandomZoom((-0.2, 0.2)),
  tf.keras.layers.RandomTranslation(height_factor=(-0.1, 0.1), width_factor=(-0.1, 0.1)),
  tf.keras.layers.RandomContrast((.2, 1.8))
])

Note:

Below are displays of augmented images.

In [14]:
plt.figure(figsize=[15,10])
for tr_image, _ in training.take(1):
    augmented_image = data_augmentation(tr_image)
    plt.imshow(augmented_image)
In [15]:
AUTOTUNE = tf.data.AUTOTUNE
In [16]:
training = training.map(lambda x, y: (data_augmentation(x, training=True), y), 
                num_parallel_calls=AUTOTUNE)
WARNING: AutoGraph could not transform <function <lambda> at 0x7f2ddc0b4ef0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
In [17]:
plt.figure(figsize=[15, 10])
for image, _ in training.take(1):
    plt.imshow(image)
In [18]:
training = training.map(normalize_and_resize)
validation = validation.map(normalize_and_resize)
testing = testing.map(normalize_and_resize)
WARNING: AutoGraph could not transform <function normalize_and_resize at 0x7f2ddc2d4560> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
In [19]:
# TODO: Create a pipeline for each set.
training_batches = training.shuffle(num_training_examples//4).batch(batch_size).prefetch(1)
validation_batches = validation.cache().batch(batch_size).prefetch(1)
testing_batches = testing.cache().batch(batch_size).prefetch(1)

Visualize our normalized image and print info about it

Note:

The images shown below are for the augmented images, so they will look a little funny.

In [20]:
for image_batch, label_batch in training_batches.take(1):
    print(f'dtype: {str(image_batch.dtype)}')
    print(f'shape: {image_batch.shape}')
    print(f'There are {label_batch.numpy().size} images in this batch')
    print(f'Labels for this batch: \n{label_batch.numpy()}\n')
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()
    plt.figure(figsize=[8,5])
    plt.imshow(images[0], cmap=plt.cm.binary)
    plt.title(f'This flower is a(n) {class_names[str(labels[0])].title()}')
    plt.colorbar()
    plt.show()
    
for image_batch, label_batch in validation_batches.take(1):
      print(f'dtype: {str(image_batch.dtype)}')
      print(f'shape: {image_batch.shape}')
      print(f'There are {label_batch.numpy().size} images in this batch')
      print(f'Labels for this batch: \n{label_batch.numpy()}\n')
        
for image_batch, label_batch in testing_batches.take(1):
    print(f'dtype: {str(image_batch.dtype)}')
    print(f'shape: {image_batch.shape}')
    print(f'There are {label_batch.numpy().size} images in this batch')
    print(f'Labels for this batch: \n{label_batch.numpy()}')
dtype: <dtype: 'float32'>
shape: (32, 224, 224, 3)
There are 32 images in this batch
Labels for this batch: 
[ 48  45  31  16  81   3  40   3  70  87  98  59  95  70  79   6  32   3
  63  58  43  67  70  30  96  69  92  90 101  12  68  86]

dtype: <dtype: 'float32'>
shape: (32, 224, 224, 3)
There are 32 images in this batch
Labels for this batch: 
[88 54  8 37 13 52 29 67 94  7 75 58 88 89 87 86 12 83 18  5 84 85 84 81
 77 34 57 44 79 80 58 78]

dtype: <dtype: 'float32'>
shape: (32, 224, 224, 3)
There are 32 images in this batch
Labels for this batch: 
[40 76 42 63 94 45 94 19 51 46 73 70 72 93 89 10 95 72 49 75 57 75 77 45
 45 24 95 65 89 72 73 88]

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [21]:
# TODO: Build and train your network.
_URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"

feature_extractor = hub.KerasLayer(_URL, input_shape=(image_size, image_size, 3))
feature_extractor.trainable = False

model = tf.keras.Sequential([feature_extractor,
                             tf.keras.layers.Dense(102, activation='softmax')])

model.summary()
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
WARNING: AutoGraph could not transform <bound method KerasLayer.call of <tensorflow_hub.keras_layer.KerasLayer object at 0x7f2e111cb0d0>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer (KerasLayer)    (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 102)               130662    
                                                                 
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________
In [22]:
EPOCHS = 15
with tf.device('/GPU:0'):
    history = model.fit(training_batches,
                        epochs=EPOCHS,
                         validation_data=validation_batches)
Epoch 1/15
WARNING: AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x7f2e10c3c9e0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
32/32 [==============================] - ETA: 0s - loss: 4.4669 - accuracy: 0.0814WARNING: AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x7f2ddd8e4050> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
32/32 [==============================] - 83s 2s/step - loss: 4.4669 - accuracy: 0.0814 - val_loss: 3.4913 - val_accuracy: 0.2284
Epoch 2/15
32/32 [==============================] - 76s 2s/step - loss: 2.7813 - accuracy: 0.4078 - val_loss: 2.5202 - val_accuracy: 0.4775
Epoch 3/15
32/32 [==============================] - 76s 2s/step - loss: 1.9042 - accuracy: 0.6225 - val_loss: 2.0174 - val_accuracy: 0.5814
Epoch 4/15
32/32 [==============================] - 75s 2s/step - loss: 1.4070 - accuracy: 0.7539 - val_loss: 1.7263 - val_accuracy: 0.6186
Epoch 5/15
32/32 [==============================] - 75s 2s/step - loss: 1.1300 - accuracy: 0.8108 - val_loss: 1.5184 - val_accuracy: 0.6765
Epoch 6/15
32/32 [==============================] - 75s 2s/step - loss: 0.9311 - accuracy: 0.8539 - val_loss: 1.3972 - val_accuracy: 0.6843
Epoch 7/15
32/32 [==============================] - 77s 2s/step - loss: 0.8156 - accuracy: 0.8578 - val_loss: 1.2924 - val_accuracy: 0.7029
Epoch 8/15
32/32 [==============================] - 77s 2s/step - loss: 0.7077 - accuracy: 0.8814 - val_loss: 1.2131 - val_accuracy: 0.7275
Epoch 9/15
32/32 [==============================] - 77s 2s/step - loss: 0.6112 - accuracy: 0.9069 - val_loss: 1.1461 - val_accuracy: 0.7392
Epoch 10/15
32/32 [==============================] - 76s 2s/step - loss: 0.5437 - accuracy: 0.9176 - val_loss: 1.0908 - val_accuracy: 0.7520
Epoch 11/15
32/32 [==============================] - 76s 2s/step - loss: 0.4870 - accuracy: 0.9176 - val_loss: 1.0464 - val_accuracy: 0.7510
Epoch 12/15
32/32 [==============================] - 77s 2s/step - loss: 0.4341 - accuracy: 0.9324 - val_loss: 1.0171 - val_accuracy: 0.7588
Epoch 13/15
32/32 [==============================] - 77s 2s/step - loss: 0.4221 - accuracy: 0.9255 - val_loss: 0.9719 - val_accuracy: 0.7696
Epoch 14/15
32/32 [==============================] - 76s 2s/step - loss: 0.3843 - accuracy: 0.9422 - val_loss: 0.9703 - val_accuracy: 0.7676
Epoch 15/15
32/32 [==============================] - 76s 2s/step - loss: 0.3722 - accuracy: 0.9510 - val_loss: 0.9288 - val_accuracy: 0.7725
In [23]:
training_keys_to_grab = ['loss', 'accuracy']
validation_keys_to_grab = ['val_loss', 'val_accuracy']
training_dict = {key: history.history[key] for key in training_keys_to_grab}
validation_dict = {key: history.history[key] for key in validation_keys_to_grab}
In [24]:
training_metrics = pd.DataFrame(data=training_dict)
validation_metrics = pd.DataFrame(data=validation_dict)
validation_metrics.columns = ['loss', 'accuracy']
In [25]:
training_metrics['label'] = 'training'
validation_metrics['label'] = 'validation'
In [26]:
metrics = pd.concat([training_metrics, validation_metrics])
In [27]:
metrics = metrics.reset_index()
In [28]:
metrics
Out[28]:
index loss accuracy label
0 0 4.466887 0.081373 training
1 1 2.781336 0.407843 training
2 2 1.904183 0.622549 training
3 3 1.406953 0.753922 training
4 4 1.130017 0.810784 training
5 5 0.931125 0.853922 training
6 6 0.815629 0.857843 training
7 7 0.707668 0.881373 training
8 8 0.611236 0.906863 training
9 9 0.543669 0.917647 training
10 10 0.486983 0.917647 training
11 11 0.434057 0.932353 training
12 12 0.422068 0.925490 training
13 13 0.384268 0.942157 training
14 14 0.372231 0.950980 training
15 0 3.491305 0.228431 validation
16 1 2.520245 0.477451 validation
17 2 2.017360 0.581373 validation
18 3 1.726274 0.618627 validation
19 4 1.518416 0.676471 validation
20 5 1.397188 0.684314 validation
21 6 1.292361 0.702941 validation
22 7 1.213129 0.727451 validation
23 8 1.146097 0.739216 validation
24 9 1.090844 0.751961 validation
25 10 1.046448 0.750980 validation
26 11 1.017062 0.758824 validation
27 12 0.971895 0.769608 validation
28 13 0.970263 0.767647 validation
29 14 0.928813 0.772549 validation
In [29]:
acc_yticks = np.arange(0., 1.2, 0.2)
acc_yticks_labels = [f'{x:.2f}' for x in acc_yticks]
acc_xticks = np.arange(-0.5, 4.2, 0.5)
acc_xticks_labels = [f'{x:.2f}' for x in acc_xticks]
In [30]:
tr_yticks = np.arange(0., 5., 0.5)
tr_yticks_labels = [f'{x:.2f}' for x in tr_yticks]
In [31]:
tr_yticks_labels
Out[31]:
['0.00',
 '0.50',
 '1.00',
 '1.50',
 '2.00',
 '2.50',
 '3.00',
 '3.50',
 '4.00',
 '4.50']
In [32]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
#plt.figure(figsize=[20,10])
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(25, 10), sharey=False)

sns.lineplot(data=metrics, x='index', y='loss', hue='label', ax=axs[0], marker='o', linewidth=5, markersize=10)
axs[0].set_ylim([0., 4.5])
axs[0].set_xlabel('Epoch #', size=20)
axs[0].set_ylabel('Model Loss', size=20)
axs[0].set_yticklabels(tr_yticks_labels, fontdict={'fontsize':20})
axs[0].set_xticklabels(acc_xticks_labels, fontdict={'fontsize':20})
axs[0].set_title('Model Loss vs. Epoch #', size=20)
axs[0].legend(labels=['Training', 'Validation'], fontsize=20)
sns.lineplot(data=metrics, x='index', y='accuracy', hue='label', ax=axs[1], marker='o', linewidth=5, markersize=10)
axs[1].set_xlabel('Epoch #', size=20)
axs[1].set_yticklabels(acc_yticks_labels, fontdict={'fontsize':20})
axs[1].set_xticklabels(acc_xticks_labels, fontdict={'fontsize':20})
axs[1].set_ylabel('Model Accuracy', size=20)
axs[1].set_title('Model Accuracy vs. Epoch #', size=20)
axs[1].legend(labels=['Training', 'Validation'], fontsize=20)
axs[1].set_ylim([0, 1])
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [33]:
# TODO: Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(testing_batches)

print(f'A loss of {loss:.2f} was achieved on the test dataset.')
print(f'An accuracy of {accuracy:.2f} was achieved on the test dataset.')
193/193 [==============================] - 132s 683ms/step - loss: 1.0740 - accuracy: 0.7385
A loss of 1.07 was achieved on the test dataset.
An accuracy of 0.74 was achieved on the test dataset.

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [30]:
model_name = 'dl_model'
model_file_path = f'./{model_name}.h5'
In [31]:
# TODO: Save your trained model as a Keras model.
model.save(model_file_path)

NOTE:

Everything below this point is for the original network with no data augmentation. I never saved the network that incorporated data augmentation since the performance was similar on the test set for both of the networks - with and without data augmentation.

Load the Keras Model

Load the Keras model you saved above.

In [32]:
# TODO: Load the Keras model
reloaded_model = tf.keras.models.load_model(model_file_path, custom_objects={'KerasLayer': hub.KerasLayer})

reloaded_model.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer (KerasLayer)    (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 102)               130662    
                                                                 
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [33]:
image_size = 224
In [34]:
# TODO: Create the process_image function
def process_image(image: np.array):
    ''' Process an image
    
        Process an image such that it is compatible
        with our neural network
        
        params:
            image - a path to an image
    '''
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, [image_size, image_size])
    image /= 255
    image = image.numpy().squeeze()
    return image

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [35]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [36]:
# TODO: Create the predict function
def predict(image_path: str, model, top_k=5):
    ''' Predicts the top k classes of an image
    
        params:
            image_path - a path to an image
            model - a Keras model saved as a HDF5
            top_k - the number of top classes
    '''
    image = Image.open(image_path) # create an Image object
    image = np.asarray(image) # cast image as a numpy.array
    image = np.expand_dims(process_image(image), 0) # add extra dimension
    
    predictions = model.predict(image)[0] # predict classes/probabilities for image
    
    # sort the predictions and take the largest top_k of them
    probabilities = np.sort(predictions)[-top_k:len(predictions)]
    probabilities = probabilities.tolist() # cast probabilities as a list
    
    ''' partition the array against the top_kth probability and return
        the indices (also the classes) of the top_k probabilities.
        
        convert top_classes to a list for plotting purposes.
        
        shift each class by 1 and convert to string
        in order to obtain the names from the .json that maps 
        classes to flower names.
        
        lastly, return a tuple containing the probabilies and
        the top classes.
    '''
    top_classes = np.argpartition(predictions, -top_k)[-top_k:]
    top_classes = top_classes.tolist()
    top_classes = [str(x + 1) for x in top_classes]
    return probabilities, top_classes

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [37]:
flowers_to_check = ['cautleya_spicata.jpg', 'hard-leaved_pocket_orchid.jpg', 'orange_dahlia.jpg',
                    'wild_pansy.jpg']
In [38]:
# TODO: Plot the input image along with the top 5 classes
fig, axs = plt.subplots(figsize=(20,40), nrows=4, ncols=2)
first_col = 0
second_col = 1
for axis, flower in zip(axs, flowers_to_check):
    name = flower.split('.')[0].replace('_', ' ').title()
    im = Image.open(f'./test_images/{flower}')
    test_image = np.asarray(im)
    processed_test_image = process_image(test_image)
    axis[first_col].imshow(processed_test_image)
    axis[first_col].set_title(f'Image of a {name}')
    
    probabilities, classes = predict('./test_images/' + flower, reloaded_model)
    names = [class_names[x] for x in classes]
    sns.barplot(y=names, x=probabilities, color='blue', ax=axis[second_col])
    axis[second_col].set_title(f'Top 5 Flower Species for {name}')
    axis[second_col].set_xlabel('Probability')
    axis[second_col].set_yticklabels(labels=names, fontdict={'fontsize':12,
                                                             'fontweight': 1000})
    plt.setp(axis[second_col].get_yticklabels(), rotation=30)
WARNING: AutoGraph could not transform <function Model.make_predict_function.<locals>.predict_function at 0x7f7660dfddd0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
In [ ]: